const { app, dialog } = require('electron')
const http = require('http')
const fs = require('fs')
const path = require('path')

//
// 下载函数
exports.downloadFile = (url, window) => {
  const arr = url.split('/')
  // 弹出文件保存对话框
  const savePath = dialog.showOpenDialogSync(window, {
    // defaultPath: path.join(app.getPath('downloads'), arr[arr.length - 1]),
    defaultPath: app.getPath('downloads'),
    // defaultPath: arr[arr.length - 1],
    properties: ['openDirectory'],
    filters: [
      { name: 'Images', extensions: ['jpg', 'png', 'gif'] },
      { name: 'Movies', extensions: ['mkv', 'avi', 'mp4'] },
      { name: 'Custom File Type', extensions: ['as'] },
      { name: 'All Files', extensions: ['*'] },
    ],
  })

  if (!savePath) return console.log('File download cancelled.')

  const file = fs.createWriteStream(savePath[0] + '\\' + arr[arr.length - 1])

  http
    .get(url, function (response) {
      response.pipe(file)
      file.on('finish', function () {
        file.close()
        console.log('File downloaded successfully:', savePath)
      })
    })
    .on('error', function (err) {
      fs.unlink(savePath)
      console.error('Error downloading file:', err.message)
    })
}
